﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Transform/Remove Scale And Rotation",
            "Remove scale and rotation from a transform and it's children keeping their positions.",
            ContextRequirements.SingleItem, 0)]
        public static void TransformRemoveScaleAndRotation()
        {
            const string undoLabel = "Remove Scale And Rotation";
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                Undo.RecordObject(context, undoLabel);

#if UNITY_2019_1_OR_NEWER
                if (PrefabUtility.IsPartOfAnyPrefab(context))
                    PrefabUtility.UnpackPrefabInstance(context.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
#endif

                var t = context.transform.GetAllChildren(true).ToArray();
                var p = new Transform[t.Length];
                for (int i = 0; i < t.Length; i++) { Undo.RecordObject(context, undoLabel); p[i] = t[i].parent; t[i].SetParent(null, true); }
                for (int i = 0; i < t.Length; i++) { t[i].localRotation = Quaternion.identity; t[i].localScale = Vector3.one; t[i].SetParent(p[i], true); }
                //break;

            }
            SkinnContext.Finished();
        }
    }
}